<template>
	<!-- 小纸条/聊天列表 -->
	<view class="chat">
		<!-- 聊天列表 -->
		<!-- 方式一：通过js计算高度控制：scroll-view高度 -->
		<!-- <scroll-view :style="`height:${scrollHeight}px;`" scroll-y="true"> -->
		<!-- 方式二：通过css布局控制：scroll-view高度 -->
		<scroll-view ref="chatScroll" class="chat-scroll" scroll-y="true" :scroll-into-view="'chat-item-'+scrollIndex"
			:scroll-with-animation="true" @scrolltoupper="onScrollToTop">
			<!-- 消息列表：绑定id，用于滚动到该元素  -->
			<chat-list v-for="(item,index) in list" :key="index" :item="item" :id="'chat-item-'+index"
				:pretime="index > 0 ? list[index-1].createTime : 0"></chat-list>
		</scroll-view>

		<!-- 底部操作栏 -->
		<bottom-input @submit="submit"></bottom-input>
	</view>
</template>

<script>
	import ChatList from "@/pages/platform/paper/cpns/chat-list.vue"
	import BottomInput from "@/pages/platform/paper/cpns/bottom-input.vue"
	export default {
		components: {
			ChatList,
			BottomInput
		},
		data() {
			return {
				scrollIndex: 0, // 滚动条定位为到哪条消息
				showIndex: 0, // 下标小于showMinIdx的消息不显示，否则可能很卡
				list: [],
				queryParam: {
					pageNum: 0,
					pageSize: 20,
					toId: undefined
				},
				total: 0,
				chooseUser: {},
				fromUserId: undefined,
				message: {
					fromId: undefined,
					toId: undefined,
					content: '',
					type: '0',
					status: '0'
				}
			}
		},
		onLoad(options) {
			this.chooseUser.id = this.message.toId = this.queryParam.toId = options.uid;
			this.fromUserId = this.message.fromId = this.vuex_user.id
			this.init()
		},
		methods: {
			onScrollToTop() {

				if (this.showIndex == 0) {
					// console.log("消息已滚动到顶部")
					return;
				}
				if (this.queryParam.pageNum > 1) {
					this.previousMessageRecord()
				}
				// 防止滚动条定格在顶部，不能一直往上滚
				this.scrollToIndex(this.showIndex);
				// 多展示0条信息
				this.showIndex = this.showIndex > this.queryParam.pageSize ? this.showIndex - this.queryParam.pageSize : 0;

			},
			init() {
				this.$u.api.messageData.userMessageRecord(this.queryParam).then(res => {
					if (res.data.records.length > 0) {
						this.list = res.data.records
						this.queryParam.pageNum = res.data.current
						this.total = res.data.total
						this.showIndex = this.list.length > this.queryParam.pageSize ? this.list.length - this
							.queryParam.pageSize : 0;
						const isFrom = this.list[0].fromId === this.vuex_user.id
						this.chooseUser.name = isFrom ? this.list[0].toName : this.list[0].fromName
						this.chooseUser.avatar = isFrom ? this.list[0].toAvatar : this.list[0].fromAvatar
						this.setChatNavigationBarTitle(this.chooseUser.name)
						// 滚动到底部
						this.scrollToBottom()
					} else {
						this.$u.api.messageData.messageUserInfo({
							userId: this.chooseUser.id
						}).then(res => {
							this.chooseUser.name = res.data.name
							this.chooseUser.avatar = res.data.avatar
							this.setChatNavigationBarTitle(this.chooseUser.name)
						})
					}
				})

				this.initWebSocket()
			},
			initWebSocket() {
				uni.$on('getMessage', (data) => {
					this.handleWsMessage(JSON.parse(data))
				});
			},
			handleWsMessage(sendMessage) {
				if (sendMessage.fromId === this.chooseUser.id) {
					sendMessage.toName = this.vuex_user.name
					sendMessage.toAvatar = this.vuex_user.avatar
					sendMessage.fromName = this.chooseUser.name
					sendMessage.fromAvatar = this.chooseUser.avatar
					this.list.push(sendMessage)
					// 滚动到底部
					this.scrollToBottom()
				}
			},
			setChatNavigationBarTitle(titleString) {
				uni.setNavigationBarTitle({
					title: titleString
				})
			},
			previousMessageRecord() {
				this.queryParam.pageNum--
				this.$u.api.messageData.userMessageRecord(this.queryParam).then(res => {
					this.list.unshift(...res.data.rows)
				})

			},
			// 发送消息
			submit(content) {
				this.message.content = content
				this.$u.api.messageData.send(this.message).then(res => {
					this.list.push(res.data)
					uni.$emit('sendMessage', res.data);
				})
				// 滚动到底部
				setTimeout(() => {
					this.scrollToBottom()
				}, 500)
			},

			scrollToIndex(index) {
				// 如果scrollIndex值没变化，滚动条不会移动
				if (index == this.scrollIndex && index > 0) {
					this.$nextTick(() => {
						// 先滚动到上一条
						this.scrollIndex = index - 1;
						// 再滚动目标位置
						this.scrollToIndex(index);
					});
					return;
				}
				this.$nextTick(() => {
					this.scrollIndex = index;
				});

			},
			// 滚动到底部
			scrollToBottom() {
				const lastIndex = this.list.length
				if (lastIndex < 0) return
				this.$nextTick(() => {
					this.scrollToIndex(lastIndex - 1);
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #f8f8f8;
	}

	.chat {

		// 通过绝对定位控制scroll-view高度
		.chat-scroll {
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 100rpx;
		}
	}
</style>